package com.example.glidedemo.transformation;


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

import androidx.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import java.security.MessageDigest;

public class WatermarkTransformation extends BitmapTransformation {
    private String watermarkText;

    // 构造方法：传入水印文字
    public WatermarkTransformation(String text) {
        super();
        this.watermarkText = text;

    }

    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {

        Bitmap.Config originalConfig = toTransform.getConfig();

        // 创建一个新的Bitmap，其颜色格式与原始Bitmap相同
        Bitmap bitmap = toTransform.copy(originalConfig, true);
        // 创建一个新的 Bitmap（与原图尺寸相同）
        Bitmap result = Bitmap.createBitmap(
                bitmap.getWidth(),
                bitmap.getHeight(),
                bitmap.getConfig()
        );

        // 创建画布，绘制原始图片
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(bitmap, 0, 0, null);

        // 配置画笔（水印文字）
        Paint paint = new Paint();
//        paint.setColor(Color.WHITE);
        paint.setColor(Color.RED);
        paint.setTextSize(40);
        paint.setAlpha(180); // 半透明

        // 计算文字位置（右下角，留出边距）
        float x = bitmap.getWidth() - paint.measureText(watermarkText) - 20;
        float y = bitmap.getHeight() - 20;

        // 绘制水印
        canvas.drawText(watermarkText, x, y, paint);

        // 回收原始 Bitmap，避免内存泄漏
        if (bitmap != result) {
            bitmap.recycle();
        }

        return result;
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

    }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    @Override
    public int hashCode() {
        return 0;
    }
}